import os
import sys
import logging
from time import strftime
import logging.handlers

# 输出日志路径
PATH = os.path.abspath('.') + '/logs/'
# 确保日志目录存在
if not os.path.exists(PATH):
    os.makedirs(PATH)  # 如果不存在则创建目录
# 设置日志格式和时间格式
FMT = '%(asctime)s %(filename)s [line:%(lineno)d] %(levelname)s: %(message)s'
DATEFMT = '%Y-%m-%d %H:%M:%S'


class MyLog(object):
    def __init__(self):
        self.logger = logging.getLogger("default")
        # self.formatter = logging.Formatter(fmt=FMT, datefmt=DATEFMT)
        self.formatter = logging.Formatter('%(asctime)s.%(msecs)03d %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
        self.log_filename = '{0}{1}.log'.format(PATH, strftime("%Y-%m-%d"))

        # 使用自定义的文件handler
        self.logger.addHandler(self.get_file_handler())
        self.logger.addHandler(self.get_console_handler())
        # 设置日志的默认级别
        self.logger.setLevel(logging.INFO)

    # 输出到文件handler的函数定义
    def get_file_handler(self):
        # 使用自定义的TimedRotatingFileHandler
        filehandler = CustomTimedRotatingFileHandler(self.log_filename, when="midnight", interval=1, backupCount=7, encoding="utf-8")
        filehandler.setFormatter(self.formatter)
        return filehandler

    # 输出到控制台handler的函数定义
    def get_console_handler(self):
        console_handler = logging.StreamHandler(sys.stdout)
        console_handler.setFormatter(self.formatter)
        return console_handler


class CustomTimedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler):
    def doRollover(self):
        self.baseFilename = '{0}{1}.log'.format(PATH, strftime("%Y-%m-%d"))
        super().doRollover()


log = MyLog().logger
